/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fork;

import java.util.HashMap;
import tal.drivechain.chain.ChainNode;
import tal.drivechain.chain.NodeListener;
import tal.drivechain.plugin.Channel;
import tal.drivechain.plugin.Module;
import tal.drivechain.system.Globals;
import tal.drivechain.variable.Variable;
import tal.drivechain.variable.types.DataType;
import tal.drivechain.variable.types.HashmapType;

/**
 *
 * @author Tal Eisenberg
 */
public class NodeEvents extends Module implements NodeListener {
    private ChainNode node = null;

    @Override
    protected void msgReceived(Variable in, long timestamp, Channel channel) {
    }

    public void setNode(String nodePath) {
        if (nodePath==null) {
            if (node!=null) {
                if (isRunning())
                    node.removeNodeListener(this);
                node = null;
            }
        }
        else {
            ChainNode n = Globals.findNode(nodePath, this.getParentChain());
            if (node!=null && isRunning()) node.removeNodeListener(this);
            node = n;
            if (isRunning()) node.addNodeListener(this);
        }
    } public String getNode() {
        if (node!=null)
            return node.getPath();
        else return null;
    }

    @Override
    public void start() {
        super.start();
        if (node!=null)
            node.addNodeListener(this);
    }

    @Override
    public void stop() {
        if (node!=null)
            node.removeNodeListener(this);
        super.stop();
    }

    Variable msgReceived = new Variable("msgReceived", new HashmapType(DataType.VAR), new HashMap(), true);

    public void messageReceived(ChainNode src, Variable var, Channel channel, long timestamp) {
        HashMap val = (HashMap)msgReceived.getInternalValue();
        val.clear();
        val.put("name", var.getName());
        val.put("val", var.getValue(src));
        val.put("channel", channel.getName());
        val.put("timestamp", timestamp);
        sendToOutputs(msgReceived, -1);
    }

    public void messageSent(ChainNode src, Variable var, long timestamp) {
    }

    public void nameChanged(ChainNode src) {
    }

    public void metaChanged(ChainNode src) {
    }

    public void connectionsChanged(ChainNode src) {
    }

    public void nodeDestroyed(ChainNode src) {
    }

    public void nodeMoved(ChainNode src) {
    }

    public void propertyChanged(ChainNode src, String name, Object value) {
    }
}
